package io.renren.modules.lucky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.CodeGenerator;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.validator.Assert;
import io.renren.modules.app.constants.ListConstants;
import io.renren.modules.app.utils.JwtUtils;
import io.renren.modules.app.utils.QrCodeCreateUtil;
import io.renren.modules.lucky.dao.AppUserInfoDao;
import io.renren.modules.lucky.dao.AppUserScoreDao;
import io.renren.modules.lucky.dao.AppUserSmsDao;
import io.renren.modules.lucky.entity.AppUserInfoEntity;
import io.renren.modules.lucky.entity.AppUserScoreEntity;
import io.renren.modules.lucky.entity.AppUserSmsEntity;
import io.renren.modules.lucky.service.AppUserInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("appUserInfoService")
public class AppUserInfoServiceImpl extends ServiceImpl<AppUserInfoDao, AppUserInfoEntity> implements AppUserInfoService {

    @Autowired
    private AppUserSmsDao appUserSmsDao;

    @Autowired
    private AppUserInfoDao appUserInfoDao;

    @Autowired
    private AppUserScoreDao scoreDao;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AppUserInfoEntity> page = this.page(
                new Query<AppUserInfoEntity>().getPage(params), new QueryWrapper<AppUserInfoEntity>()
        );
        return new PageUtils(page);
    }

    @Transactional(readOnly = false)
    public Map<String, Object> validPhone(String phoneNum, String smsCode) {

        Map<String, Object> map = new HashMap<String, Object>();
        // 手机号是否正确
        if (StringUtils.isEmpty(phoneNum) || phoneNum.length() != 11) {
            map.put("ret", "2");
            map.put("info", "不是合法的手机号码");
            return map;
        }

        // 验证码是否正确
        AppUserSmsEntity smsEntity = appUserSmsDao.selectOne(new QueryWrapper<AppUserSmsEntity>()
                .eq("phone_num", phoneNum).eq("sms_code", smsCode).eq("sms_flag", 1));
        map.clear();
        if (smsEntity == null) {
            map.put("ret", "3");
            map.put("info", "验证码不正确");
            return map;
        }

        // 设置该号码下所有登陆验证码失效
        smsEntity = new AppUserSmsEntity();
        smsEntity.setSmsFlag(0);
        appUserSmsDao.update(smsEntity, new QueryWrapper<AppUserSmsEntity>().eq("phone_num", phoneNum)
                .eq("sms_code", smsCode));

        // 获取用户信息
        List<AppUserInfoEntity> userList = baseMapper.selectList(new QueryWrapper<AppUserInfoEntity>().eq("user_phone", phoneNum));
        Map<String, Object> userMap = new HashMap<String, Object>();
        // 走注册分支
        if (userList.isEmpty()) {
            AppUserInfoEntity infoEntity = new AppUserInfoEntity();
            infoEntity.setUserPhone(phoneNum);
            infoEntity.setUserFlag(1);
            // 生成token
            infoEntity.setUserToken(CodeGenerator.generateUUID());
            infoEntity.setLoginTime(new Date());
            infoEntity.setCreateTime(new Date());
            boolean boo = retBool(baseMapper.insert(infoEntity));
            if (!boo) {
                map.put("ret", "0");
                map.put("info", "注册失败");
                return map;
            } else {
                userList = baseMapper.selectList(new QueryWrapper<AppUserInfoEntity>().eq("user_phone", phoneNum));
                map.put("ret", "1");
                map.put("info", "下一步填写用户密码");
                map.put("infoEntity", userList.get(0));
                return map;
            }
        }
        AppUserInfoEntity infoEntity = userList.get(0);

        map.put("ret", "4");
        map.put("info", "用户验证码登录");
        map.put("infoEntity", infoEntity);
        // 生成token
        String token = jwtUtils.generateToken(infoEntity.getId());
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        return map;
    }

    @Transactional(readOnly = false)
    public AppUserInfoEntity register(String phoneNum, String userPwd, String userToken, String inviteCode) {
        //根据用户电话与token判断用户是否真实注册
        AppUserInfoEntity infoEntity = baseMapper.selectOne(new QueryWrapper<AppUserInfoEntity>().eq("user_phone", phoneNum)
                .eq("user_token", userToken));
        Assert.isNull(infoEntity, "虚假用户注册");
        // 生成用户二维码
        String userInvite = QrCodeCreateUtil.createUserInviteCode(phoneNum);
        // 更新登陆信息
        infoEntity.setUserPwd(userPwd);
        infoEntity.setUserCode(userInvite);
        boolean boo = retBool(baseMapper.update(infoEntity, new QueryWrapper<AppUserInfoEntity>().eq("user_phone", phoneNum)
                .eq("user_token", userToken)));
        if (boo) {
            infoEntity.setUserPwd(userPwd);
        }
        AppUserScoreEntity score = ListConstants.insertScore("register", infoEntity.getId());
        scoreDao.insert(score);
        //根据邀请码（用户电话）
        if(!inviteCode.equals("")) {
            AppUserInfoEntity user = appUserInfoDao.selectOne(new QueryWrapper<AppUserInfoEntity>().eq("user_code", inviteCode));
            if (user != null) {
                score = ListConstants.insertScore("pushNewUser", user.getId());
                scoreDao.insert(score);
            }
        }
        return infoEntity;
    }

    @Transactional(readOnly = false)
    public AppUserInfoEntity login(String phoneNum, String userPwd) {
        // 用户是否存在
        AppUserInfoEntity infoEntity = baseMapper.selectOne(new QueryWrapper<AppUserInfoEntity>().eq("user_phone", phoneNum)
                .eq("user_pwd", userPwd));
        Assert.isNull(infoEntity, "账号或密码有误");

        // 更新登陆信息
        String token = CodeGenerator.generateUUID();
        infoEntity.setLoginTime(new Date());
        infoEntity.setUserToken(token);
        baseMapper.update(infoEntity, new QueryWrapper<AppUserInfoEntity>().eq("user_phone", phoneNum)
                .eq("user_pwd", userPwd));
        AppUserScoreEntity score = ListConstants.insertScore("login", infoEntity.getId());
        scoreDao.insert(score);
        return infoEntity;
    }

    @Override
    public Map<String, Object> queryUserInfo(String user_id, String user_token) {
        String id = jwtUtils.getClaimByToken(user_token).getSubject();
        if (id.equals(user_id)) {
            Map<String, Object> map = appUserInfoDao.getUserInfo(Integer.parseInt(user_id));
            Assert.isNull(map, "用户不存在");
            return map;
        } else {
            throw new RRException("请求用户id与token不匹配");
        }
    }

    public int saveUserInfo(AppUserInfoEntity infoEntity, String user_token) {
        String id = jwtUtils.getClaimByToken(user_token).getSubject();
        if (id.equals(infoEntity.getId().toString())) {
            int num = baseMapper.update(infoEntity, new QueryWrapper<AppUserInfoEntity>()
                    .eq("id", infoEntity.getId()));
            return num;
        } else {
            throw new RRException("请求用户id与token不匹配");
        }
    }

    @Override
    public AppUserInfoEntity queryOrRegistUserByPhoneNum(String phoneNum) {
        // 获取用户信息
        AppUserInfoEntity entity = queryUserInfo(phoneNum);
        // 走注册分支
        if (entity == null) {
            AppUserInfoEntity infoEntity = new AppUserInfoEntity();
            infoEntity.setUserPhone(phoneNum);
            infoEntity.setUserFlag(1);
            // 生成token
            infoEntity.setUserToken(CodeGenerator.generateUUID());
            // 生成用户二维码
            String userInvite = QrCodeCreateUtil.createUserInviteCode(phoneNum);
            infoEntity.setUserCode(userInvite);
            infoEntity.setLoginTime(new Date());
            infoEntity.setCreateTime(new Date());
            boolean boo = retBool(baseMapper.insert(infoEntity));
            if (!boo) {
                System.out.println("新增用户失败！");
                return null;
            }
            entity = infoEntity;
        }
        return entity;
    }

    @Override
    public AppUserInfoEntity queryUserInfo(String phone) {
        // 获取用户信息
        List<AppUserInfoEntity> userList = baseMapper.selectList(new QueryWrapper<AppUserInfoEntity>().eq("user_phone", phone));
//        AppUserInfoEntity entity = null;
        if (!userList.isEmpty()) {
            return userList.get(0);
        }
        return null;
    }

}